package com.pig4cloud.commcon.websocket;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

public class WebSocketCommon {
	/**
	 * 保存已登录的会话session
	 */
	public static ConcurrentHashMap<String, WebSocketSession> CLIENT_SESSION = new ConcurrentHashMap();

	public static String getMapKey(WebSocketSession session){
		Object userId = session.getAttributes().get(WebSocketConstants.TOKEN);
		if(userId==null){
			return null;
		}
		String useridStr = userId.toString();
		return useridStr;
	}


	/**
	 * 后台发送消息到前端
	 * 封装方法发送消息到客户端
	 */
	public static void sendMessage(String message) throws IOException {
		ConcurrentHashMap.KeySetView<String,WebSocketSession> userIds = CLIENT_SESSION.keySet();
		for (String userId : userIds) {
			WebSocketSession session = CLIENT_SESSION.get(userId);
			session.sendMessage(new TextMessage(message));
		}
	}


}
